<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <wx-tables
    :columns="columns"
    title="轮播管理"
    :data-source="dataSource"
    :loading="loading"
    :total="total"
    :size.sync="size"
    :page.sync="page"
    @handlePage="handlePage"
  >
    <!-- tools -->
    <template #tools>
      <el-button type="primary" class="table-btn" @click="handleOpenForm()">新增轮播</el-button>
      <!--      <el-button class="table-btn" icon="el-icon-refresh-right" @click="handleGetTable">刷新</el-button>-->
    </template>
    <template v-slot:position="record">
      <span>{{ BANNER_POSITION[record.row.position] }}</span>
    </template>
    <template v-slot:img="record">
      <el-avatar shape="square" :size="100" fit="cover" :src="record.row.img"></el-avatar>
    </template>
    <template v-slot:status="record">
      <el-switch
        v-model="record.row.status"
        :active-value="1"
        :inactive-value="0"
        active-color="#409EFF"
        inactive-color="#C0CCDA"
        @change="handleSetStatus(record.row)">
      </el-switch>
    </template>
    <template v-slot:oper="record">
      <div class="oper-box">
        <span><el-link type="primary" @click="handleEit(record.row)">编辑</el-link></span>
        <el-popconfirm
          title="确定删除当前轮播内容吗？"
          @confirm="handleDelete(record.row.id)"
        >
          <el-link slot="reference" type="danger">删除</el-link>
        </el-popconfirm>
      </div>
    </template>
    <wx-dialog
      ref="wx-dialog"
      :visible.sync="formVisible"
      :is-add="isAdd"
      width="600px"
      @ok="handleSaveForm"
    >
      <div class="wx-dialog-form">
        <el-form ref="ruleForm" v-loading="formLoading" :rules="ruleForm" :model="formInfo" label-position="left" label-width="90px">
          <el-form-item label="轮播位置" prop="position">
            <el-select v-model="formInfo.position" clearable placeholder="请选择轮播位置">
              <el-option
                v-for="(item, type) of BANNER_POSITION"
                :key="type"
                :label="item"
                :value="Number(type)"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="关联内容" prop="target_type">
            <el-radio-group @change="handleEmpty" v-model="formInfo.target_type">
              <el-radio :label="0">无</el-radio>
              <el-radio :label="1">内置商品</el-radio>
              <el-radio :label="2">外部链接</el-radio>
            </el-radio-group>
            <el-input  v-model="formInfo.target" style="width: 200px;"
                       :disabled="formInfo.target_type !== 2"
                       :placeholder="formInfo.target_type === 2 ? '请输入外部链接' : '请选择商品'" />
            <el-button class="m-l-16" :disabled="formInfo.target_type !== 1"
                       @click="handleChange"
                       size="mini" type="primary" round>请选择商品</el-button>
          </el-form-item>
          <el-form-item label="图片" prop="img">
            <el-upload
              class="up-load"
              :class="formInfo.img && formInfo.img.length > 0 ? 'hidden':''"
              action="https://up.qiniup.com"
              :limit="1"
              :data="uploadData"
              accept="image/*"
              :file-list="formInfo.img"
              list-type="picture-card"
              :before-upload="beforeAvatarUpload"
              :on-success="upSuccess"
              :on-exceed="overMax"
              :on-remove="handleRemove"
            >
              <i slot="default" class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
    </wx-dialog>

    <wx-dialog
      ref="wx-dialog"
      title="选择商品"
      :visible.sync="shopVisible"
      :is-add="isAdd"
      width="500px"
      @ok="shopVisible = false"
    >
      <div class="wx-dialog-form">
        <el-input placeholder="请输入内容" v-model="searchText" class="input-with-select">
          <el-button @click="handleSearch" slot="append" icon="el-icon-search"></el-button>
        </el-input>
        <div class="hight-box">
          <div v-if="!shopList.length" style="margin-top: 12px;cursor: default">
            <span>暂无商品</span>
          </div>
          <el-radio-group v-else v-model="target" @change="changeTarget">
            <div v-for="item in shopList" :key="item.id" style="margin-top: 12px">
              <el-radio v-model="item.id" :label="item.id">{{ item.name }}</el-radio>
            </div>
          </el-radio-group>
        </div>
      </div>
    </wx-dialog>
  </wx-tables>
</template>

<script>
import { adminPortalResetPassword } from '@/api/login'
import WxDialog from '@/components/WxDialog'
import WxTables from '@/components/WxTables'
import TableMixins from '@/components/WxTables/mixins'
import { BANNER_POSITION } from '@/views/constants'
import { sysBannerCreate, sysBannerDestroy, sysBannerEdit, sysBannerGetListByCon } from '@/api/banner'
import { tourProductGetListByCon } from '@/api/merchant'
export default {
  name: 'CarouselManagement',
  components: {
    WxDialog,
    WxTables
  },
  mixins: [TableMixins],
  data() {
    return {
      pwdDialog: false,
      columns: [
        { config: { type: 'index', width: 100 }, label: '序号' },
        { dataIndex: 'position', label: '轮播位置', slots: true },
        { dataIndex: 'img', label: '图片', slots: true },
        { dataIndex: 'created_at', label: '创建时间' },
        { dataIndex: 'status', label: '是否启用', slots: true },
        { dataIndex: 'oper', label: '操作', slots: true }
      ],
      target: '',
      searchText: '',
      roleList: [],
      shopList: [],
      shopAllList: [],
      markId: '',
      BANNER_POSITION,
      ruleForm: {
        position: [
          { required: true, message: '请选择轮播位置', trigger: 'blur' }
        ],
        img: [
          { required: true, message: '请上传图片', trigger: 'blur' }
        ]
      },
      shopVisible: false
    }
  },
  watch: {
    formVisible(val) {
      if(val && !this.formInfo.target_type) this.$set(this.formInfo,'target_type',0)
    },
    shopVisible(val) {
      if(!val) this.shopList = this.shopAllList
    }
  },
  mounted() {
    this.getShopList()
  },
  methods: {
    /**
     * 获取列表
     */
    getList() {
      sysBannerGetListByCon({town_id: this.town_id,page: this.page}).then(res => {
        if (this.pagination) {
          const { data, total } = res.data
          this.total = total
          this.dataSource = data
          this.cacheDataSource = JSON.parse(JSON.stringify(data))
        } else {
          this.dataSource = res.data
          this.cacheDataSource = JSON.parse(JSON.stringify(res.data))
        }
        this.handleSetCancelStatus?.()
        // this.handleCompleteTable()
      }).finally(() => {
        this.loading = false
      })
    },
    /**
     * 选择商品
     */
    changeTarget() {
      const val = this.shopAllList.filter(res=>res.id === this.target)[0].name
      this.$set(this.formInfo,'target',val)
    },
    /**
     * 获取商品列表
     */
    getShopList(search_word) {
      tourProductGetListByCon({town_id:this.town_id,search_word}).then(res => {
        this.shopList = res.data.data
        if(search_word) {
          this.$message.success('查找成功')
        }else{
          this.shopAllList = JSON.parse(JSON.stringify(res.data.data))
        }
      })
    },
    /**
     * 新增/编辑人员
     */
    createManager(idSend) {
      const { img, position, target, target_type } = this.formInfo
      let from_info = {
        position,
      }
      from_info.target_type = target_type ? target_type : 0
      from_info.target = target ? target : ''
      if(from_info.target_type === 1) {
        if(!from_info.target) return this.$message.warning('请选择商品')
        from_info.target = this.shopAllList.filter(res=>res.name === from_info.target)[0].id
      }
      from_info.img = img[0].name ? this.img_url + img[0].response.key  : this.img_url + img[0].uid
      if(Object.keys(idSend).length) {
        sysBannerEdit({ ...from_info,...idSend,town_id: this.town_id })
          .then((res) => {
            if (res.code === 200) {
              this.$message.success(this.isAdd ? '添加成功' : '编辑成功')
              this.formInfo = {}
              this.formVisible = false
              this.handleGetTable()
            }
          }).finally(() => {
          this.handleResetDialog()
        })
      }else{
        sysBannerCreate({ ...from_info,town_id: this.town_id })
          .then((res) => {
            if (res.code === 200) {
              this.$message.success(this.isAdd ? '添加成功' : '编辑成功')
              this.formInfo = {}
              this.formVisible = false
              this.handleGetTable()
            }
          }).finally(() => {
          this.handleResetDialog()
        })
      }
    },
    /**
     * 编辑
     * @param item
     */
    handleEit(item) {
      let { id, position, img, target ,target_type } = item
      img = img ? [{ url: img, uid: img.substring(img.lastIndexOf('/')+1) }] : []
      if(target_type === 1) {
        this.target = Number(target)
        target = this.shopAllList.filter(res=>res.id === this.target)[0].name
      }
      this.markId = 'sys_banner_id'
      this.handleOpenForm(id,['position','img','target','target_type'],{position,img,target,target_type})
    },
    /**
     * 删除
     * @param admin_ids
     */
    handleDelete(sys_banner_ids) {
      sysBannerDestroy({ sys_banner_ids }).then((res) => { if (res.code === 200) {
        this.$message.success(res.msg)
        this.handleGetTable()
      } })
    },
    /**
     * 搜索商品
     */
    handleSearch() {
      this.getShopList(this.searchText)

    },
    /**
     * 选择商品
     */
    handleChange() {
      this.shopVisible = true
      this.searchText = ''
    },
    /**
     * 确认选择的商品
     */
    handleConfirm() {

    },
    /**
     * 监控上传数量
     */
    overMax() {
      this.$message.warning({ message: '上传图片最大为1张' })
    },
    /**
     * 得到上传成功的文件
     * @param fileList
     * @param type
     */
    getFile(fileList,type) {
      this.$set(this.formInfo,'img',fileList)
    },
    /**
     * 删除图片
     * @param fileList
     */
    deleteFile(fileList) {
      this.$set(this.formInfo,'img',fileList)
    },
    /**
     * 变化清空
     */
    handleEmpty() {
      this.$set(this.formInfo,'target','')
    },
    /**
     * 翻页
     * @param val
     */
    handlePage(val) {
      this.page = val
    }
  }
}
</script>
<style lang="scss" src="./style/index.scss" scoped/>
<style scoped>
.m-l-16 {
  margin-left: 16px;
}
.up-load {
  height: 174px;
}
.hidden >>> .el-upload--picture-card {
  display: none;
}
::v-deep .el-avatar>img {
  width: 100%;
}
.hight-box {
  height: 400px;
  margin-top: 12px;
  overflow-y: auto;
}
</style>
